// file: services/movie_service.go

package services

import (
	"punch-in/datamodels"
	"punch-in/repositories"
	"punch-in/s/utils"
	"time"
)

var punch = &datamodels.Punch{Account: "peng.yu", AccountId: 1}

type PunchService interface {
	GetAll(page int, limit int) []datamodels.Punch
	GetByID(id int64) map[string]interface{}
	GetByDate() map[string]interface{}
	GetWeeks() map[int]string
	GetTimes() []string
	GetCurWeek() int
	GetCurTime() string
	UpdatePosterAndGenreByID(id int64, morning uint8, noon uint8, night uint8) int64
}

func NewPunchService(repo repositories.PunchRepository) PunchService {
	return &punchService{
		repo: repo,
	}
}

type punchService struct {
	repo repositories.PunchRepository
}

func (s *punchService) GetAll(page int, limit int) []datamodels.Punch {
	if page < 1 {
		page = 1
	}
	if page > 10000 {
		page = 10000
	}
	offset := (page - 1) * limit
	return s.repo.SelectMany(punch, offset, limit)
}

func (s *punchService) GetByID(id int64) map[string]interface{} {
	punch.Id = id
	return s.getPunchInfo()
}

func (s *punchService) GetByDate() map[string]interface{} {
	punch.Day = utils.NowYmd()
	return s.getPunchInfo()
}

/**
 * 获取当前时间，例：12:00
 */
func (s *punchService) GetCurTime() string {
	var curTime string
	switch hour := time.Now().Hour(); {
	case hour < 10:
		curTime = "08:00"
	case hour < 12:
		curTime = "10:00"
	case hour < 14:
		curTime = "12:00"
	case hour < 16:
		curTime = "14:00"
	case hour < 18:
		curTime = "16:00"
	default:
		curTime = "18:00"
	}
	return curTime
}

/**
 * 获取当前星期数 例：Monday
 */
func (s *punchService) GetCurWeek() int {
	weekday := int(time.Now().Weekday())
	if weekday == 0 {
		weekday = 7
	}
	return weekday
}

/**
 * 获取周枚举数据
 */
func (s *punchService) GetWeeks() (shortDayNames map[int]string) {
	shortDayNames = map[int]string{
		1: "Mon",
		2: "Tue",
		3: "Wed",
		4: "Thu",
		5: "Fri",
		6: "Sat",
		7: "Sun",
	}
	return
}

/**
 * 获取间隔时间枚举数据
 */
func (s *punchService) GetTimes() (timeNames []string) {
	timeNames = []string{
		"08:00",
		"10:00",
		"12:00",
		"14:00",
		"16:00",
		"18:00",
	}
	return
}

func (s *punchService) getPunchInfo() map[string]interface{} {
	data, has := s.repo.Select(punch)
	if false == has {
		return map[string]interface{}{
			"morning": 0,
			"noon":    0,
			"night":   0,
			"id":      0,
		}
	}
	return map[string]interface{}{
		"id":      data.Id,
		"morning": data.Morning,
		"noon":    data.Noon,
		"night":   data.Night,
		"day":     data.Day.Format("2006-01-02"),
	}
}

func (s *punchService) UpdatePosterAndGenreByID(id int64, morning uint8, noon uint8, night uint8) int64 {
	if id > 0 {
		punch.Id = id
	}
	if morning > 0 {
		punch.Morning = 1
	}
	if noon > 0 {
		punch.Noon = 1
	}
	if night > 0 {
		punch.Night = 1
	}
	return s.repo.InsertOrUpdate(punch)
}
